<template>
    <div class="mapWrapper" v-loading="isLoading">
        <!-- 地图容器 -->
        <div id="mapContainer"></div>
    </div>
    
</template>
    
<script setup>
    import { reactive,ref } from 'vue'
    import {BMapRequester,GoodsRequester} from '@/api/api.js'
    import {useRouter} from 'vue-router'

    const mapRqster =new BMapRequester("itQ3DWgrPP7fdS26ALG8ht4FgEYaV8rT");
    const goodsRqster = new GoodsRequester();

    const router = useRouter();
    
    const longitude = "119.19567108154297";
    const latitude = "29.575429778924"

    //地图组件的加载
    let isLoading = ref(true);

    //起始点坐标
    //var point = new BMap.Point(119.2043099519231, 26.064666454604797);
    const startX = ref(119.195000);
    const startY = ref(26.055000);
    //地图展示的商品

    let goodsForShow = reactive([

    ])


    const loadNewGoods = async function(){
        let  {data} = await  goodsRqster.reqNearGoods(startX.value,startY.value,10);
        /* goodsRqster.reqNearGoods(startX.value,startY.value,10).then(res=>{
            data = res.data;
        }) */

        for (let good of data){
            /* //获取转换后的坐标
            let result = await mapRqster.reqCoordsConvert(good.latitude,good.longitude);
            //赋值给good后，push到goodsForShow中
            good.latitude = result.data.result[0].x;
            good.longitude = result.data.result[0].y; */
            goodsForShow.push(good);
        }
        
        loadMapScript();

        /*  mapRqster.reqCoordsConvert(startX.value,startY.value).then(res=>{
            console.log('转换后的坐标如下:',res);
            startX.value=res.data.result[0].x;
            startY.value=res.data.result[0].y;
        }).catch(err=>{
            console.log('转换出错！');
            console.log(err);
        }).then(res=>{
            //起始坐标转换后开始加载地图
            loadMapScript();
        }) */
    };


    

//初始化地图信息
const initMap=()=>{
        console.log('mapInit');
        var map = new BMap.Map('mapContainer');
        //var point = new BMap.Point(119.2043099519231, 26.064666454604797); 
        var point = new BMap.Point(119.19625091552734, 26.056652069091797); 
        //设置地图中心与放大倍数
        map.centerAndZoom(point,18) 
        
        //设置地图样式（皮肤），并且可以自定义
        map.setMapStyleV2({     
            styleId: 'df833c5a841d8896444c0982d007ff8b'
    });
    
    //定位
    function myFun(result){
        var cityName = result.name;
        /*  map.setCenter(cityName); */
        console.log("当前定位城市:"+cityName);
    }
    var myCity = new BMap.LocalCity();
    myCity.get(myFun); 
    
    //创建标注
    var iconSrcList = reactive([
        require('@/assets/images/icon/home/摄影定位.png'),
        require('@/assets/images/icon/home/书籍定位1.png'),
        require('@/assets/images/icon/home/书籍定位2.png'),
        require('@/assets/images/icon/home/耳机定位.png'),
        require('@/assets/images/icon/home/汽车定位.png'),
       /*  require('@/assets/images/icon/home/yellow_location.svg'),
        require('@/assets/images/icon/home/green_location.svg'),
        require('@/assets/images/icon/home/pink_location.svg'),
        require('@/assets/images/icon/home/blue_location.svg'), */
    ]);

    for (let good of goodsForShow){
        let myIconSrc = iconSrcList[Math.floor(Math.random()*iconSrcList.length)]
        let myIcon = new BMap.Icon(myIconSrc, new BMap.Size(64, 64), {   
        // 指定定位位置。  
        // 当标注显示在地图上时，其所指向的地理位置距离图标左上   
        // 角各偏移10像素和25像素。您可以看到在本例中该位置即是  
        // 图标中央下端的尖角位置。   
        /* anchor: new BMap.Size(10, 25),    */
        // 设置图片偏移。  
        // 当您需要从一幅较大的图片中截取某部分作为标注图标时，您  
        // 需要指定大图的偏移位置，此做法与css sprites技术类似。   
        imageOffset: new BMap.Size(0, 0 )   // 设置图片偏移   
        });     
        var goodpoint = new BMap.Point(good.latitude,good.longitude);
        let marker = new BMap.Marker(goodpoint,{icon:myIcon}); 
        map.addOverlay(marker); 

        //点击跳转商品详情
        marker.addEventListener("click", function(){  
            console.log('点击标注！'); 
            router.push({
                name:'goodsDetail',
                params:{
                    goodsId:good.goodsId,
                    userId:1
                }
            })
        });  
    }

    


}

const loadMapScript = () => {
    // 此处在所需页面引入资源就是，不用再public/index.html中引入
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.className = "loadmap"; // 给script一个类名
    script.src =
    "https://api.map.baidu.com/api?v=3.0&ak=itQ3DWgrPP7fdS26ALG8ht4FgEYaV8rT";
    // 此处需要注意：申请ak时，一定要应用类别一定要选浏览器端，不能选服务端，不然地图会报ak无效
    script.onload = () => {
        // 使用script.onload，待资源加载完成，再初始化地图
        initMap();
    };
    let loadmap = document.getElementsByClassName("loadmap");
    if (loadmap) {
        // 每次append script之前判断一下，避免重复添加script资源标签
        for (var i = 0; i < loadmap.length; i++) {
            document.body.removeChild(loadmap[i]);
        }
    }
    
    document.body.appendChild(script);
    setTimeout(()=>{
        isLoading.value=false;
    },1000)
};

loadNewGoods();

    
//在setup中初始化地图
//loadMapScript();




</script>

<style lang="scss" scoped>

/* 商品分类 */
.mapWrapper{
    
    height: 4.1rem;
    position: relative;

    /* 地图容器 */
    #mapContainer{
        
        
        height: 100%;
    }
}

</style>